package com.example.leo.mycharmingstudent.mvp.source.remote;

import com.example.leo.mycharmingstudent.a0917.practice.ArticleEntity;
import com.example.leo.mycharmingstudent.a0917.practice.HandlerUtil;
import com.example.leo.mycharmingstudent.mvp.source.IMVPTasksDataSource;
import com.example.leo.mycharmingstudent.project.constant.ApiInterface;
import com.example.leo.mycharmingstudent.project.util.OkHttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Leo on 2020/11/10.
 */

public class MVPTasksRemoteDataSource implements IMVPTasksDataSource {
    @Override
    public void articleList(int currentPage, final NetCallBack<ArticleEntity> netCallBack) {
        String url = String.format(Locale.CHINA, ApiInterface.ARTICLE_URL, currentPage);
        OkHttpUtil.enqueue(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                final ArticleEntity articleEntity = new Gson().fromJson(result, ArticleEntity.class);
                HandlerUtil.post(new Runnable() {
                    @Override
                    public void run() {
                        netCallBack.onResponse(articleEntity);
                    }
                });
            }
        });
    }

    private static MVPTasksRemoteDataSource INSTANCE;

    private MVPTasksRemoteDataSource() {
    }

    public static MVPTasksRemoteDataSource getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MVPTasksRemoteDataSource();
        }
        return INSTANCE;
    }
}
